﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FinanSoft.Entities;
using FinanSoft.BusinessLayer;
using FinanSoft.Utilities;
using FinanSoft.DataLayer;

namespace FinanSoft.PresentacionContabilidad
{
    public partial class frmConsultaAsientos : Form
    {
        int[] _typesIds;
        frmAsientos frmAsiento;
        AccountingEntry currentEntry;

        public frmConsultaAsientos(frmAsientos frmAsientoV_)
        {
            frmAsiento = frmAsientoV_;
            InitializeComponent();
            fillFields();
        }

        private void fillFields()
        {
            fillCodes();
        }

        private void ClearFields()
        {
            while (gridAsientos.Rows.Count > 1)
            {
                gridAsientos.Rows.RemoveAt(0);
            }

            gridAsientos.Rows.Clear();
            cbDocType.SelectedIndex = - 1;
            cbIgnoreDate.Checked = false;
            txtRef1.Text = "";
            txtRef2.Text = "";
            txtRef3.Text = "";
            txtSeason.Text = "";
            dtpFechaFin.Value = System.DateTime.Now;
            dtpFechaIni.Value = System.DateTime.Now;

            gridAsientos.Update();  

        }

        private void SetFields(bool value)
        {
            cbDocType.Enabled = value;
            cbIgnoreDate.Enabled = value;
            txtRef1.Enabled = value;
            txtRef2.Enabled = value;
            txtRef3.Enabled = value;
            dtpFechaIni.Enabled = value;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FetchPreviousEntry();
        }

        private void btnSalir_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void fillCodes()
        {
            List<DocType> docTypes = DocumentTypeManager.GetInstance().Types;
            _typesIds = new int[docTypes.Count];
            for (int currencyIndex = 0; currencyIndex < docTypes.Count; currencyIndex++)
            {
                _typesIds[currencyIndex] = docTypes[currencyIndex].Id;
                cbDocType.Items.Add(docTypes[currencyIndex].Name);
            }

            cbDocType.SelectedIndex = cbDocType.Items.Count - 1;
        }

        private void FetchNextEntry()
        {
            AccountingEntry temp;

            ClearFields();
            temp = AccountingEntryCacheManager.GetInstance().FetchNext();

            if (AccountingEntryCacheManager.GetInstance().IsError)
            {
                MessageBox.Show(AccountingEntryCacheManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ShowAccountingEntry();
            }
            else
            {
                currentEntry = temp;
                ShowAccountingEntry();
            }

            SetFields(false);
        }

        private void FetchPreviousEntry()
        {
            AccountingEntry temp;

            ClearFields();
            temp = AccountingEntryCacheManager.GetInstance().FetchPrevious();

            if (AccountingEntryCacheManager.GetInstance().IsError)
            {
                MessageBox.Show(AccountingEntryCacheManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ShowAccountingEntry();
            }
            else
            {
                currentEntry = temp;
                ShowAccountingEntry();
            }

            SetFields(false);
        }

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            AccountingEntry temp;
            int typeId;

            typeId = cbDocType.SelectedIndex == -1 ? Constants.INVALID_ID : _typesIds[cbDocType.SelectedIndex];

            if(cbIgnoreDate.Checked)
                temp = AccountingEntryCacheManager.GetInstance().UpdateCache(typeId, dtpFechaIni.Value, txtRef1.Text, txtRef2.Text, txtRef3.Text, true);
            else
                temp = AccountingEntryCacheManager.GetInstance().UpdateCache(typeId, dtpFechaIni.Value, txtRef1.Text, txtRef2.Text, txtRef3.Text, false);

            if (AccountingEntryCacheManager.GetInstance().IsError)
            {
                MessageBox.Show(AccountingEntryCacheManager.GetInstance().ErrorMessage, MessageConstants.TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
            else
            {
                ClearFields();
                currentEntry = temp;
                SetFields(false); //Desactiva los campos para evitar modificar los parametros mientras se exploran los resultados de la busqueda.
                ShowAccountingEntry();
                btnBuscar.Enabled = false;
            }
            
        }

        private void ShowAccountingEntry()
        {
            DataGridViewRow newRow;
            String accName;

            if (currentEntry == null)
                return;

            cbDocType.Text = currentEntry.Type.Name;
            txtRef1.Text = currentEntry.Ref1;
            txtRef2.Text = currentEntry.Ref2;
            txtRef3.Text = currentEntry.Ref3;
            dtpFechaFin.Value = currentEntry.DocDate;
            dtpFechaIni.Value = currentEntry.AccountingDate;
            txtSeason.Text = currentEntry.Season.Name;            

            foreach (AccountingEntryDetail detail in currentEntry.EntryDetails)
            {
                newRow = new DataGridViewRow();
                newRow.CreateCells(gridAsientos);
                accName = detail.AuxiliarAccountId == -1 ? detail.Account.Name : AuxiliaryAccountManager.GetInstance().GetAuxiliarAccount(detail.AuxiliarAccountId).Name;
                string localSymbol = MoneyManager.GetInstance().LocalCurrency.Symbol;
                string systemSymbol = MoneyManager.GetInstance().SystemCurrency.Symbol;
                object[] parameters = detail.Type == Constants.AccountingEntryType.credit ? new object[] { accName, 0, localSymbol + detail.LocAmmount.ToString("0.00"), 0, systemSymbol + detail.SysAmmount.ToString("0.00") } : 
                    new object[] { detail.Account.Name, localSymbol + detail.LocAmmount.ToString("0.00"), 0, systemSymbol + detail.SysAmmount.ToString("0.00"), 0 };
                
                newRow.SetValues(parameters);
                gridAsientos.Rows.Add(newRow);
            }

            verifySet();

        }

        private void verifySet()
        {
            if (!hasNext())
                btnSiguiente.Enabled = false;
            else
                btnSiguiente.Enabled = true;
            if (!hasPrevious())
                btnPrevious.Enabled = false;
            else
                btnPrevious.Enabled = true;
        }

        private bool hasNext()
        {
            return AccountingEntryCacheManager.GetInstance().hasNext();
        }

        private bool hasPrevious()
        {
            return AccountingEntryCacheManager.GetInstance().hasPrevious();
        }

        private void btnLimpiar_Click(object sender, EventArgs e)
        {
            ClearFields();
            SetFields(true); //Activa los campos para realizar una nueva búsqueda
            btnBuscar.Enabled = true;
        }

        private void btnSiguiente_Click(object sender, EventArgs e)
        {
            FetchNextEntry();
        }
    }
}
